package com.dnndo.web.controller.common;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.code.kaptcha.Producer;
import com.dnndo.common.config.RuoYiConfig;
import com.dnndo.common.constant.CacheConstants;
import com.dnndo.common.constant.Constants;
import com.dnndo.common.constant.RedisConstant;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.core.domain.entity.SysUser;
import com.dnndo.common.core.redis.RedisCache;
import com.dnndo.common.exception.CustomExceptions;
import com.dnndo.common.utils.SmsUtil;
import com.dnndo.common.utils.StringUtils;
import com.dnndo.common.utils.sign.Base64;
import com.dnndo.common.utils.uuid.IdUtils;
import com.dnndo.system.domain.vo.CaptchaImageVO;
import com.dnndo.system.service.ISysConfigService;
import com.dnndo.system.service.ISysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码、短信 操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private ISysUserService userService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public R<CaptchaImageVO> getCode() {
        CaptchaImageVO vo = new CaptchaImageVO();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        vo.setCaptchaEnabled(captchaEnabled);
        if (!captchaEnabled)
        {
            return R.ok(vo);
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return R.fail("验证码生成失败，请稍后重试");
        }
        vo.setUuid(uuid);
        vo.setImg(Base64.encode(os.toByteArray()));
        return R.ok(vo);
    }

    /**
     * 校验图片验证码
     */
    @GetMapping("/validateCaptcha")
    public R<?> validateCaptchaCode(@ApiParam(value = "图片验证码",required = true) String captcha,
                                 @ApiParam(value = "唯一码",required = true) String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captchaRedis = redisCache.getCacheObject(verifyKey);
        if (captchaRedis == null) {
            return R.fail("验证码过期，请重新输入");
        }
        if (!captcha.equalsIgnoreCase(captchaRedis)) {
            return R.fail("验证码错误，请重新输入");
        }
        return R.ok();
    }

    /**
     * 发送短信验证码（图形验证码版）
     *
     * @param phone   手机号
     * @param uuid    唯一码
     * @param captcha 图片验证码验证码
     * @return AjaxResult
     */
    @GetMapping("/sendSms")
    public R<?> sendSms(@ApiParam(value = "手机号",required = true) String phone,
                              @ApiParam(value = "唯一码",required = true) String uuid,
                              @ApiParam(value = "图片验证码",required = true) String captcha) {
        //验证验证码
        validateCaptcha(captcha, uuid);
        return sendSms(phone);
    }

    /**
     * 发送短信验证码（直接发送版）
     *
     * @param phone 手机号
     * @return AjaxResult
     */
    @GetMapping("/sendSmsNoCaptcha")
    @ApiImplicitParam(name = "Authorization", value = "登录标识(token)", required = true, dataType = "String",paramType = "header")
    public R<?> sendSmsNoCaptcha(@ApiParam(value = "手机号",required = true) String phone) {
        return sendSms(phone);
    }

    /**
     * 发送注册验证码，判断是否已经注册
     */
    @GetMapping("/sendRegisterSms")
    public R<?> validateCaptcha(@ApiParam(value = "手机号",required = true) String phone,
                                      @ApiParam(value = "唯一码",required = true) String uuid,
                                      @ApiParam(value = "图片验证码",required = true) String captcha) {
        //验证验证码
        validateCaptcha(captcha, uuid);
        //根据手机号查询是否已经有这个用户
        SysUser user = userService.getOne(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, phone)
                .eq(SysUser::getDelFlag, 0));
        if (user != null) {
            return R.fail(201, "该手机号已注册");
        }
        return sendSms(phone);
    }

    /**
     * 发送找回密码验证码，判断你是否有此用户
     */
    @GetMapping("/sendForgetPwdSms")
    public R<?> sendForgetPwdSms(@ApiParam(value = "手机号",required = true) String phone,
                                @ApiParam(value = "唯一码",required = true) String uuid,
                                @ApiParam(value = "图片验证码",required = true) String captcha) {
        //验证验证码
        validateCaptcha(captcha, uuid);
        //根据手机号查询是否已经有这个用户
        long count = userService.count(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, phone)
                .eq(SysUser::getDelFlag, 0));
        if (count <= 0) {
            return R.fail(201, "该手机号未注册");
        }
        return sendSms(phone);
    }


    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @return 结果
     */
    private R<?> sendSms(String phone) {
        //判断一分钟内是否已经发送验证码
        if (redisCache.hasKey(RedisConstant.SMS_CODE_COUNT_KEY + phone)) {
            return R.fail("发送过于频繁，请稍后重试");
        }
        String code = RandomUtil.randomNumbers(4);
        //写入Redis 有效期五分钟
        redisCache.setCacheObject(RedisConstant.SMS_CODE_KEY + phone, code, 5, TimeUnit.MINUTES);
        //写入次数到Redis
        redisCache.setCacheObject(RedisConstant.SMS_CODE_COUNT_KEY + phone, 1, 1, TimeUnit.MINUTES);
        smsUtil.sendSms(phone, code);
        return R.ok();
    }

    /**
     * 校验图片验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null) {
            throw new CustomExceptions("验证码过期，请重新输入");
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CustomExceptions("验证码错误，请重新输入");
        }
    }
}
